package com.gitee.ywj1352.classloader;

import java.io.*;
import java.util.HashMap;

/**
 * @author wenjie.yang on 2019/11/18.
 */
public class MyCl extends ClassLoader{

    private HashMap<String,Class> classes = new HashMap();
    private String classpath;
    private String jarName;

    public MyCl(String classpath, String jarName) {
        this.classpath = classpath;
        this.jarName = jarName;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if(!name.startsWith("com.yy")){
            return super.loadClass(name);
        }
        if(classes.containsKey(name)){
            return classes.get(name);
        }
        try {
            byte [] classDate=getDate(name);
            if(classDate==null){

            }else{
                //defineClass方法将字节码转化为类
//                 defineClass(name,classDate,0,classDate.length);
                Class c =  defineClass(name, classDate, 0, classDate.length, null);
                classes.put(name,c);
                return  c;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.loadClass(name);
    }
    //返回类的字节码
    private byte[] getDate(String className) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;
        byte[] data = null;
        try {
            is = new FileInputStream(new File("C:\\ywj\\Thread1.class"));
            int c = 0;
            while (-1 != (c = is.read())) {
                baos.write(c);
            }
            data = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    public static void main(String[] args) throws Exception{
        MyCl myCl = new MyCl("", "");
        Class<?> hah = myCl.loadClass("com.yy.Thread1");
        Object o = hah.newInstance();
        System.out.println(o);

    }

}
